package isquirrel.servlets;

import isquirrel.error.CannotLoginUserException;
import isquirrel.semantic.DBpedia;
import isquirrel.servlets.handler.HttpDBServlet;

import java.io.IOException;
import java.util.Vector;
import java.util.concurrent.ConcurrentLinkedQueue;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONException;
import org.json.JSONObject;

/**
 * Servlet implementation class GetDesc
 */
public class GetDesc extends HttpDBServlet implements Runnable {
	private static final long serialVersionUID = 1L;
    
	
	private Vector<Desc> _descriptions = new Vector<Desc>();
	private ConcurrentLinkedQueue<String[]> _tokens = new ConcurrentLinkedQueue<String[]>();
	private int _threads = 0; 
	
	private synchronized void incThreads(){
		++_threads;
	}
	
	private synchronized void decThreads(){
		--_threads;
	}
	
	
    /**
     * @see HttpServlet#HttpServlet()
     */
    public GetDesc() {
        super();
    }

	@Override
	protected void handleGet() throws ServletException, IOException,
			JSONException, CannotLoginUserException {
		DBpedia db = new DBpedia();
		String subject = request.getParameter("subject");
		int type = Integer.valueOf(request.getParameter("type"));
	
		// if the parameter is a url list
		if (type == 1){
			JSONObject jresponse = new JSONObject();
			String[] urlnumpairs = subject.split(",");
			
			for (int i = 0; i < urlnumpairs.length; ++i){
				
				String[] tokens = urlnumpairs[i].split("-");
				_tokens.add(tokens);
				
				Thread thread = new Thread(this);
				thread.start();
				
			}
			
			while(_threads > 0){
				try {
					Thread.sleep(100);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
			
			while( !_descriptions.isEmpty() ){
				Desc d = _descriptions.remove(0);
				jresponse.put(d.where(), d.what());
			}
			writeAjaxResponse(jresponse);
		}
		else{
			response.getWriter().print(db.getDescription(subject));		
		}
	}

	@Override
	protected void handlePost() throws ServletException, IOException,
			JSONException, CannotLoginUserException {
		// TODO Auto-generate method stub
		
	}

	@Override
	public void run() {
		incThreads();
		DBpedia db = new DBpedia();
		String[] tokens = _tokens.remove();
		_descriptions.add(new Desc("abs_" + tokens[0] + "page_0", db.getDescription(tokens[1])));
		decThreads();
	}
	
	class Desc {
		
		private String where = null;
		private String what  = null;
		
		public Desc(String a, String b){
			
			where = a;
			what = b;
		}
		
		public String where() {
			return where;
		}
		
		public String what(){
			return what;
		}
		
	}

}
